package com.jy.appmarket.activity;

import it.gmariotti.cardslib.library.view.PullToRefreshListView;

import java.util.List;

import android.app.ActionBar;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Parcelable;
import android.text.Spannable;
import android.text.SpannableStringBuilder;
import android.text.TextUtils;
import android.text.style.ForegroundColorSpan;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import com.github.johnpersano.supertoasts.SuperActivityToast;
import com.github.johnpersano.supertoasts.SuperToast;
import com.github.johnpersano.supertoasts.util.OnClickWrapper;
import com.jy.app.market.idata.data.Comment;
import com.jy.app.market.idata.data.CommentList;
import com.jy.appmarket.AppMarketApplication;
import com.jy.appmarket.R;
import com.jy.appmarket.adapter.CommentAdapter;
import com.jy.appmarket.dialog.TextDialog;
import com.jy.appmarket.download.DownloadActivity;
import com.jy.appmarket.download.DownloadItem;
import com.jy.appmarket.download.DownloadService;
import com.jy.appmarket.download.DownloadUtils;
import com.jy.appmarket.network.engine.ApkCommentEngine;
import com.jy.appmarket.network.engine.BaseNetEngine;
import com.jy.appmarket.network.resultdata.ApkCommentResult;
import com.jy.appmarket.network.resultdata.BaseResultData;
import com.jy.appmarket.network.task.NetTask;
import com.jy.appmarket.network.task.NetTask.NetTaskListener;
import com.jy.appmarket.statistics.ApkSource;
import com.jy.appmarket.utils.LogUtil;
import com.jy.appmarket.view.LoadingView;
import com.umeng.analytics.MobclickAgent;

public class AppCommentActivity extends DownloadActivity implements NetTaskListener,
		PullToRefreshListView.RefreshingListener, OnClickListener {
	private static final String TAG = "AppCommentActivity";

	public static final String EXTRA_NAME = "comment_name";
	public static final String EXTRA_PKG = "comment_package";
	public static final String EXTRA_VERSIONCODE = "comment_vc";

	public static final String EXTRA_DLURL = "comment_dlurl";
	public static final String EXTRA_ICONURL = "comment_iconurl";
	public static final String EXTRA_VERSIONNAME = "comment_versionname";
	public static final String EXTRA_MD5 = "comment_md5";
	public static final String EXTRA_FILESIZE = "comment_fileSize";

	private static final int NET_TAG_INFO_LIST = 1;
	private static final int REQ_CODE_COMMIT = 1003;
	private static final int REQ_CODE_LOGIN = 1006;

	private PullToRefreshListView mListView;
	private LoadingView mLoadingView;
	private NetTask mNetTask;
	private int mNextPage = 1;
	private int mTotalPage;

	private boolean mbFooterRefreshing = false;
	private CommentAdapter mAdapter;

	private String mName;
	private String mPkgName;
	private int mVersionCode;
	private String mDlUrl;
	private String mIconUrl;
	private String mVersionName;
	private String mMd5;
	// private int mFileSize;
	private boolean mCommented = false;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_appcomment);
		getData();
		initViews();
		startGetComments();
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		if (mNetTask != null) {
			mNetTask.cancel();
			mNetTask.setListener(null);
			mNetTask = null;
		}

	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case android.R.id.home:
			finish();
			break;
		default:
			break;
		}
		return super.onOptionsItemSelected(item);
	}

	private void initViews() {
		ActionBar actionBar = getActionBar();
		actionBar.setTitle(R.string.comment);
		actionBar.setDisplayUseLogoEnabled(false);
		actionBar.setDisplayShowHomeEnabled(false);
		actionBar.setDisplayHomeAsUpEnabled(true);

		mAdapter = new CommentAdapter(this);
		mListView = findViewById(R.id.appcomment_listview);
		mListView.needToRefreshOnFooter(false);
		mListView.needToRefreshOnHeader(true);
		mListView.setAdapter(mAdapter);
		mListView.setRefreshListener(this);
		findViewById(R.id.appcomment_submit).setOnClickListener(this);
		mLoadingView = findViewById(R.id.loading_view_layout);
	}

	private void getData() {
		Intent it = getIntent();
		if (it == null) {
			return;
		}
		mName = it.getStringExtra(EXTRA_NAME);
		mPkgName = it.getStringExtra(EXTRA_PKG);
		mVersionCode = it.getIntExtra(EXTRA_VERSIONCODE, 0);

		mDlUrl = it.getStringExtra(EXTRA_DLURL);
		mIconUrl = it.getStringExtra(EXTRA_ICONURL);
		mVersionName = it.getStringExtra(EXTRA_VERSIONNAME);
		mMd5 = it.getStringExtra(EXTRA_MD5);
		// mFileSize = it.getIntExtra(EXTRA_FILESIZE, 0);
	}

	private void startGetComments() {
		if (mLoadingView.getVisibility() == View.VISIBLE) {
			mLoadingView.showWaitView(R.string.ptr1_loading_wait);
		}
		ApkCommentEngine engine = new ApkCommentEngine(mPkgName, mVersionCode, mNextPage);
		mNetTask = new NetTask(this, engine, NET_TAG_INFO_LIST);
		mNetTask.setListener(this);
		new Thread(mNetTask).start();
	}

	private void updateCommentSummary(int good, int bad, int other) {
		final TextView title = findViewById(R.id.app_comment_percentage);
		int total = good + bad + other;
		if (total == 0) {
			title.setText("应用评论（0）");
			total = Integer.MAX_VALUE;
		} else {
			title.setText("应用评论（" + total + "）");
		}

		TextView percent = findViewById(R.id.app_comment_percentage);
		int p = (int) (good * 100.0 / total);
		percent.setText(String.valueOf(p));

		final ProgressBar likeRate = findViewById(R.id.app_comment_like_progress);
		final TextView likeCount = findViewById(R.id.app_comment_like_count_text);

		final ProgressBar dislikeRate = findViewById(R.id.app_comment_dislike_progress);
		final TextView dislikeCount = findViewById(R.id.app_comment_dislike_count_text);
		int bigger = Math.max(good, bad);
		if (bigger <= 200) {
			likeRate.setMax(200);
			dislikeRate.setMax(200);
		} else if (bigger <= 500) {
			likeRate.setMax(500);
			dislikeRate.setMax(500);
		} else if (bigger <= 1000) {
			likeRate.setMax(1000);
			dislikeRate.setMax(1000);
		} else {
			likeRate.setMax(bigger);
			dislikeRate.setMax(bigger);
		}

		likeRate.setProgress(good + 1);
		dislikeRate.setProgress(bad + 1);

		likeCount.setText(good + "好评");
		dislikeCount.setText(bad + "差评");
	}

	private void showEmptyView() {
		findViewById(R.id.app_comment_discription).setVisibility(View.GONE);
		findViewById(R.id.appcomment_submit_layout).setVisibility(View.VISIBLE);
		mListView.setVisibility(View.GONE);
		mLoadingView.setVisibility(View.VISIBLE);
		mLoadingView.showEmptyView("暂无评论");
	}

	@Override
	public void onTaskRunSuccessful(int tag, BaseNetEngine engine) {
		BaseResultData baseResult = engine.getResultData();
		if (tag == NET_TAG_INFO_LIST) {
			findViewById(R.id.app_comment_discription).setVisibility(View.VISIBLE);
			findViewById(R.id.appcomment_submit_layout).setVisibility(View.VISIBLE);
			mListView.setVisibility(View.VISIBLE);
			mLoadingView.setVisibility(View.GONE);

			ApkCommentResult result = (ApkCommentResult) baseResult;
			CommentList list = result.getCommentList();
			mCommented = list.isCommented();
			updateCommentSummary(list.getGood(), list.getBad(), list.getOther());
			List<Comment> comments = list.getComments();
			mTotalPage = list.getTotalPage();
			mNextPage = list.getPageNo() + 1;
			LogUtil.d(TAG, mNextPage + " " + mTotalPage);
			if (mNextPage >= mTotalPage) {
				mListView.needToRefreshOnFooter(false);
			} else {
				mListView.needToRefreshOnFooter(true);
			}

			if (comments != null && comments.size() > 0) {

				List<Comment> commentList = mAdapter.getList();

				if (commentList != null && commentList.size() > 0 && mbFooterRefreshing) {
					commentList.addAll(comments);
				} else {
					mAdapter.setList(comments);
				}

				if (mbFooterRefreshing) {
					mListView.footerRefreshingCompleted();
					mAdapter.notifyDataSetChanged();
				} else {
					mAdapter.notifyDataSetChanged();
					mListView.headerRefreshingCompleted();
				}

			} else {
				showEmptyView();
			}
		}
	}

	@Override
	public void onTaskRunError(int tag) {
		if (tag == NET_TAG_INFO_LIST) {
			if (!mbFooterRefreshing) {
				if (mLoadingView.getVisibility() == View.VISIBLE) {
					findViewById(R.id.app_comment_discription).setVisibility(View.GONE);
					findViewById(R.id.appcomment_submit_layout).setVisibility(View.GONE);
					mLoadingView.showErrorView(R.string.ptrl_refresh_fail);
					mLoadingView.setOnClickListener(new View.OnClickListener() {
						@Override
						public void onClick(View v) {
							mNextPage = 1;
							startGetComments();
						}
					});
				} else {
					mListView.headerRefreshingCompleted();
				}
			} else {
				mListView.footerRefreshError();
			}
		}
	}

	@Override
	public void onTaskRunCanceled(int tag) {
		// nothing to do
	}

	@Override
	public void onHeaderRefreshing() {
		mbFooterRefreshing = false;
		mNextPage = 1;
		startGetComments();
	}

	@Override
	public void onFooterRefreshing() {
		mbFooterRefreshing = true;
		startGetComments();
	}

	private void showDownloadToast(final String name) {
		if (TextUtils.isEmpty(name)) {
			return;
		}
		SuperActivityToast satoast = new SuperActivityToast(this, SuperToast.Type.BUTTON);
		satoast.setButtonText("查看");
		String info = name + "已加入下载，点击右侧按钮可查看任务";
		if (!DownloadUtils.isMobileNetwork(this)) {
			satoast.setText(info);
			satoast.setDuration(SuperToast.Duration.LONG);
		} else {
			String gprs = "\n提示：" + getString(R.string.download_in_gprs);

			SpannableStringBuilder ssb = new SpannableStringBuilder(info + gprs);
			ssb.setSpan(new ForegroundColorSpan(Color.YELLOW), info.length(), ssb.length(),
					Spannable.SPAN_EXCLUSIVE_INCLUSIVE);
			satoast.setText(ssb);
			satoast.setDuration(SuperToast.Duration.EXTRA_LONG);
		}
		satoast.setButtonIcon(R.drawable.download_icon);
		satoast.setOnClickWrapper(new OnClickWrapper("download_app",
				new SuperToast.OnClickListener() {
					@Override
					public void onClick(View view, Parcelable token) {
						startActivity(new Intent(AppCommentActivity.this,
								DownloadManagerActivity.class));
					}
				}));
		satoast.show();
	}

	private void checkAppStatus() {
		final String dlId = DownloadUtils.generateDownloadId(mPkgName, mVersionCode);
		int status = getDownloadStatus(null, mPkgName, mVersionCode);
		switch (status) {
		case DownloadService.STATUS_INSTALLED:
		case DownloadService.STATUS_NEED_TO_UPDATE:{
			// check login
			if (AppMarketApplication.isLogin()) {
				// submit comment
				gotoSubmit();
			} else {
				Toast.makeText(this, "登录以后才可以评论", Toast.LENGTH_SHORT).show();
				startActivityForResult(new Intent(this, UserLoginActivity.class), REQ_CODE_LOGIN);
			}
		}
			break;
		case DownloadService.STATUS_CAN_INSTALL: {
			final DownloadItem di = getDownloadById(dlId);

			final TextDialog dialog = new TextDialog(this);
			dialog.showTitle(R.string.prompt).setContent(mName + "还没有安装，安装后才可以评论")
					.showButton1(getString(R.string.cancel), new View.OnClickListener() {
						@Override
						public void onClick(View v) {
							dialog.cancel();
						}
					}).showButton2(getString(R.string.install), new View.OnClickListener() {
						@Override
						public void onClick(View v) {
							dialog.cancel();
							installApk(di);
						}
					}).show();
		}
			break;
		case DownloadService.STATUS_NO_STATUS: {
			final TextDialog dialog = new TextDialog(this);
			dialog.showTitle(R.string.prompt).setContent(mName + "还没有安装，安装后才可以评论")
					.showButton1(getString(R.string.cancel), new View.OnClickListener() {
						@Override
						public void onClick(View v) {
							dialog.cancel();
						}
					}).showButton2(getString(R.string.install), new View.OnClickListener() {
						@Override
						public void onClick(View v) {
							dialog.cancel();
							addDownload(mDlUrl, mName, mPkgName, mVersionName, mVersionCode, mMd5,
									mIconUrl, new ApkSource("get_comment", mPkgName, null, null,
											null, null, null).toSourceString());
							showDownloadToast(mName);
						}
					}).show();
		}
			break;
		case DownloadService.STATUS_PENDING:
		case DownloadService.STATUS_PREPARE_TO_DOWNLOAD:
		case DownloadService.STATUS_PREPARE_TO_STOP:
		case DownloadService.STATUS_DOWNLOADING:
		case DownloadService.STATUS_INSTALLING: {
			final String tip = String.format(
					getString(R.string.apk_is_downloading_to_comment_wait), mName);
			Toast.makeText(this, tip, Toast.LENGTH_LONG).show();
		}
			break;
		case DownloadService.STATUS_PAUSED_BY_USER:
		case DownloadService.STATUS_PAUSED_BY_MOBILE_NETWORK:
		case DownloadService.STATUS_PAUSED_BY_ERROR: {
			final TextDialog dialog = new TextDialog(this);
			dialog.showTitle(R.string.prompt).setContent(mName + "已加入了下载，但没有启动，需要启动么？")
					.showButton1(getString(R.string.cancel), new View.OnClickListener() {
						@Override
						public void onClick(View v) {
							dialog.cancel();
						}
					}).showButton2("启动", new View.OnClickListener() {
						@Override
						public void onClick(View v) {
							dialog.cancel();
							startDownload(dlId);
							showDownloadToast(mName);
						}
					}).show();
		}
			break;

		// 下载过期状态，强制处理为有更新状态，点击后重新开始下载
		case DownloadService.STATUS_DOWNLOAD_OUT_OF_DATE: {

			final TextDialog dialog = new TextDialog(this);
			final String tip = String
					.format(getString(R.string.install_this_apk_to_comment), mName);

			dialog.showTitle(R.string.prompt).setContent(tip)
					.showButton1(getString(R.string.cancel), new View.OnClickListener() {
						@Override
						public void onClick(View v) {
							dialog.cancel();
						}
					}).showButton2(getString(R.string.install), new View.OnClickListener() {
						@Override
						public void onClick(View v) {
							dialog.cancel();
							removeOutofDateDownloads(mPkgName);
							addDownload(mDlUrl, mName, mPkgName, mVersionName, mVersionCode, mMd5,
									mIconUrl, new ApkSource("get_comment", mPkgName, null, null,
											null, null, null).toSourceString());
							showDownloadToast(mName);
						}
					}).show();
		}
			break;
//		case DownloadService.STATUS_NEED_TO_UPDATE: {
//			final String tip = String
//					.format(getString(R.string.install_this_apk_to_comment), mName);
//
//			final TextDialog dialog = new TextDialog(this);
//			dialog.showTitle(R.string.prompt).setContent(tip)
//					.showButton1(getString(R.string.cancel), new View.OnClickListener() {
//						@Override
//						public void onClick(View v) {
//							dialog.cancel();
//						}
//					}).showButton2(getString(R.string.install), new View.OnClickListener() {
//						@Override
//						public void onClick(View v) {
//							dialog.cancel();
//							addDownload(mDlUrl, mName, mPkgName, mVersionName, mVersionCode, mMd5,
//									mIconUrl, null);
//							showDownloadToast(mName);
//						}
//					}).show();
//		}
//			break;
		default:
			LogUtil.w(TAG, "unknown status:" + status);
			break;
		}
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.appcomment_submit:
			checkAppStatus();
			break;
		default:
			break;
		}

	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		if (resultCode != Activity.RESULT_OK) {
			LogUtil.d(TAG, "request " + requestCode + " failed with " + resultCode);
			return;
		}

		if (requestCode == REQ_CODE_COMMIT) {
			// 如果之前有任务在运行，取消掉
			if (mNetTask != null) {
				mNetTask.cancel();
				mNetTask.setListener(null);
				mNetTask = null;
			}
			// 不用管是否正在刷新，接口内部会处理的
			mListView.startHeaderRefresh();
		} else if (requestCode == REQ_CODE_LOGIN) {
			gotoSubmit();
		}

	}

	private void gotoSubmit() {
		Intent it = new Intent(this, SubmitCommentActivity.class);
		it.putExtra(SubmitCommentActivity.EXTRA_PKG, mPkgName);
		it.putExtra(SubmitCommentActivity.EXTRA_VERSIONCODE, mVersionCode);
		it.putExtra(SubmitCommentActivity.EXTRA_COMMENTED, mCommented);
		startActivityForResult(it, REQ_CODE_COMMIT);
	}

	@Override
	protected void onResume() {
		super.onResume();
		MobclickAgent.onResume(this);
	}

	@Override
	protected void onPause() {
		super.onPause();
		MobclickAgent.onPause(this);
	}
}
